import Cookie from 'js-cookie'
import axios from 'axios'
import getFingerPrint from '../network/finger.js'

let clientId
const uploadOss = async (rawFile, busType, getToken) => {
  const isBrowser = !!globalThis.location
  if (!isBrowser) return rawFile
  if (!clientId) clientId = await getFingerPrint()
  let keyPath
  let formData
  const { file, content, width, height } = rawFile

  const fnCallback = (res = {}) => {
    const { code, data: { key, token } = {} } = res
    const _formData = new FormData()
    keyPath = key
    _formData.append('file', file)
    _formData.append('key', key)
    _formData.append('token', token)
    _formData.append('x:type', busType)
    _formData.append('x:uid', Cookie.get('OP_ID'))
    _formData.append('x:deviceId', clientId)
    return (code === 0 || code === 200) ? _formData : null
  }
  if (getToken && getToken.send) {
    formData = await getToken.send({
      businessType: busType,
      fileKey: file.name,
      deviceId: clientId
    }).then(fnCallback)
  } else {
    formData = await axios.post('https://api.pjpiao.com/admin/common/getUploadToken', {
      businessType: busType,
      fileKey: file.name,
      deviceId: clientId
    }, {
      headers: {
        'Authorization': `Bearer ${Cookie.get('x-basement-token')}`
      }
    }).then(({ data, status } = {}) => fnCallback(status === 200 ? data : {}))
  }
  return formData ? await axios.post('https://upload-z2.qiniup.com/', formData, { headers: 'multipart/form-data' })
    .then(() => {
      rawFile.name = file.name
      rawFile.size = file.size
      rawFile.type = file.type
      rawFile.width = width
      rawFile.height = height
      rawFile.url = `https://static.pjpiao.com/${keyPath}`
      rawFile.content = content
      delete rawFile.file
      return rawFile
    }) : Promise.reject(new Error('获取上传token失败'))
}

export default uploadOss
